#include "./proto.h"
#include "../utils/alg.h"
#include "./conn_info.h"
#include "../utils/encode.h"
#include "../utils/decode.h"

namespace conn::proto {

using namespace utils;

uint8_t set_rs232_head(uint8_t *buf, uint8_t data_len, const ConnInfo &conn_info) {
    encode(buf, HEAD);
    buf[2] = data_len + 8;
    buf[3] = conn_info.req;
    buf[4] = conn_info.seq_type;
    buf[5] = conn_info.src_dest;

    buf[6 + data_len] = alg::sum_xor(buf + 6, data_len);
    buf[7 + data_len] = END;
    return data_len + 8;
}

SplitProtoRet split_proto(const uint8_t *buf, uint8_t len, uint8_t &index) {
    if (len < 8) {
        return SplitProtoRet::FAIL;
    }

    uint16_t head = decode<uint16_t>(buf);
    if (head != proto::HEAD) {
        return SplitProtoRet::FAIL;
    }

    uint8_t n = decode<uint8_t>(buf + 2);
    if ((n < 8) || (len < n)) {
        return SplitProtoRet::FAIL;
    }

    uint8_t sum = alg::sum_xor(buf + 6, n - 8);
    if (sum != buf[n - 2]) {
        return SplitProtoRet::FAIL;
    }

    if (buf[n - 1] != proto::END) {
        return SplitProtoRet::FAIL;
    }
    
    index = n;
    return SplitProtoRet::NEXT;
}

}
